#include "kernel_operator.h"
using namespace AscendC;

constexpr int32_t BUFFER_NUM = 2;      //昇腾双buffer技术

class KernelAsinhGrad {
public:
    __aicore__ inline KernelAsinhGrad() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR dy, GM_ADDR y,  uint32_t CoreDataNum, uint32_t finalTileNum, uint32_t tileDataNum, uint32_t TailDataNum)
    {

        ASSERT(GetBlockNum() != 0 && "block dim can not be zero!");

        this->coreDataNum = CoreDataNum;
        this->tileNum = finalTileNum;
        this->tileDataNum = tileDataNum;
        this->tailDataNum = TailDataNum;

        xGm.SetGlobalBuffer((__gm__ DTYPE_X*)x, this->coreDataNum);
        dyGm.SetGlobalBuffer((__gm__ DTYPE_DY*)dy, this->coreDataNum);
        yGm.SetGlobalBuffer((__gm__ DTYPE_Y*)y, this->coreDataNum);

        pipe.InitBuffer(inQueueX,  BUFFER_NUM, (this->tileDataNum)  * sizeof(DTYPE_X));  
        pipe.InitBuffer(inQueueDY, BUFFER_NUM, (this->tileDataNum)  * sizeof(DTYPE_DY));  
        pipe.InitBuffer(outQueueY, BUFFER_NUM, (this->tileDataNum) * sizeof(DTYPE_Y));     
        pipe.InitBuffer(QueueZero,   (this->tileDataNum )  * sizeof(DTYPE_X));     //+ 256
        //pipe.InitBuffer(QueueMask, (this->tileDataNum + 256)  * sizeof(DTYPE_X));  
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;   //手动考虑了双buff
        this->processDataNum = this->tileDataNum;
        for (int32_t i = 0; i < loopCount; i++) {
            if (i == this->tileNum - 1) {
                this->processDataNum = this->tailDataNum;
            }
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        } 
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        //考生补充算子代码
        LocalTensor<DTYPE_X> xLocal  = inQueueX.AllocTensor<DTYPE_X>();
        LocalTensor<DTYPE_DY> dyLocal = inQueueDY.AllocTensor<DTYPE_DY>();
        DataCopy(xLocal, xGm[progress * this->tileDataNum], this->processDataNum);  //tileDataNum>taileDataNum，所以不需要麻烦分情况讨论
        DataCopy(dyLocal, dyGm[progress * this->tileDataNum], this->processDataNum);
        inQueueX.EnQue(xLocal);
        inQueueDY.EnQue(dyLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {

        LocalTensor<DTYPE_X> xLocal   = inQueueX.DeQue<DTYPE_X>();
        LocalTensor<DTYPE_DY> dyLocal = inQueueDY.DeQue<DTYPE_DY>();
        LocalTensor<DTYPE_Y> yLocal   = outQueueY.AllocTensor<DTYPE_Y>();
        
        //cosh == (np.exp(x) + np.exp(-x)) / 2    不考虑大数吃小数，这里只有一个是对的

        if constexpr (std::is_same_v<DTYPE_X, int32_t>)
        {
            if(((float)xLocal.GetValue(0) < (float)80) && ((float)xLocal.GetValue(0) > (float)-80)) 
            {
                Exp(yLocal,xLocal,this->processDataNum);
                auto m_zero    = QueueZero.Get<DTYPE_X>();
                Sub(xLocal,m_zero,xLocal,this->processDataNum); 
                Exp(xLocal,xLocal,this->processDataNum);
                //Reciprocal(yLocal, xLocal, this->processDataNum);
                Add(yLocal, xLocal, yLocal, this->processDataNum);
                DTYPE_Y scalar = 0.5;
                Muls(yLocal, yLocal, scalar, this->processDataNum);
                Div(yLocal, dyLocal, yLocal, this->processDataNum);
            }
            else
            {
            // printf("yLocal %f  %f  %f %f\n",yLocal(0), yLocal(1), yLocal(2), yLocal(3)); 

            //cosh = (exp(-2y) + 1) / exp(-2y)     y > 0  考虑到大数吃小数
            //cosh = (exp(2y) + 1) /  exp(2y)        y < 0
            
                auto m_zero    = QueueZero.Get<DTYPE_X>();
                DTYPE_Y scalar = 2.00;

                if(((float)xLocal.GetValue(0) > (float)0)) 
                {
                    Sub(xLocal,m_zero,xLocal,this->processDataNum); 
                    Muls(yLocal, xLocal, scalar, this->processDataNum);  //-2y
                    Exp(xLocal, xLocal, this->processDataNum);        //x = e-y
                    Exp(yLocal, yLocal, this->processDataNum);        //y = e-2y
                    //Reciprocal(xLocal, xLocal, this->processDataNum);
                    scalar = 1.00;
                    //Mul(yLocal, xLocal, xLocal, this->processDataNum);
                    Adds(yLocal, yLocal, scalar, this->processDataNum);
                    
                    scalar = 2.00;
                    Muls(xLocal, xLocal, scalar, this->processDataNum); 
                    Div(yLocal, xLocal, yLocal, this->processDataNum);
                }
                else
                {
                    Muls(yLocal, xLocal, scalar, this->processDataNum);  // 2y
                    Exp(xLocal, xLocal, this->processDataNum);        //x = ey
                    Exp(yLocal, yLocal, this->processDataNum);        //y = e2y

                    scalar = 1.00;
                // Mul(yLocal, xLocal, xLocal, this->processDataNum);
                    Adds(yLocal, yLocal, scalar, this->processDataNum);
                    
                    scalar = 2.00;
                    Muls(xLocal, xLocal, scalar, this->processDataNum); 
                    Div(yLocal, xLocal, yLocal, this->processDataNum);
                }
                Mul(yLocal, dyLocal, yLocal, this->processDataNum);

            }
        }
        else
        {
            if(((float)xLocal.GetValue(0) < (float)10) && ((float)xLocal.GetValue(0) > (float)-10)) 
            {
                Exp(yLocal,xLocal,this->processDataNum);
                auto m_zero    = QueueZero.Get<DTYPE_X>();
                Sub(xLocal,m_zero,xLocal,this->processDataNum); 
                Exp(xLocal,xLocal,this->processDataNum);
                //Reciprocal(yLocal, xLocal, this->processDataNum);
                Add(yLocal, xLocal, yLocal, this->processDataNum);
                DTYPE_Y scalar = 0.5;
                Muls(yLocal, yLocal, scalar, this->processDataNum);
                Div(yLocal, dyLocal, yLocal, this->processDataNum);
            }
            else
            {
            // printf("yLocal %f  %f  %f %f\n",yLocal(0), yLocal(1), yLocal(2), yLocal(3)); 

            //cosh = (exp(-2y) + 1) / exp(-2y)     y > 0  考虑到大数吃小数
            //cosh = (exp(2y) + 1) /  exp(2y)        y < 0
            
                auto m_zero    = QueueZero.Get<DTYPE_X>();
                DTYPE_Y scalar = 2.00;

                if(((float)xLocal.GetValue(0) > (float)0)) 
                {
                    Sub(xLocal,m_zero,xLocal,this->processDataNum); 
                    Muls(yLocal, xLocal, scalar, this->processDataNum);  //-2y
                    Exp(xLocal, xLocal, this->processDataNum);        //x = e-y
                    Exp(yLocal, yLocal, this->processDataNum);        //y = e-2y
                    //Reciprocal(xLocal, xLocal, this->processDataNum);
                    scalar = 1.00;
                    //Mul(yLocal, xLocal, xLocal, this->processDataNum);
                    Adds(yLocal, yLocal, scalar, this->processDataNum);
                    
                    scalar = 2.00;
                    Muls(xLocal, xLocal, scalar, this->processDataNum); 
                    Div(yLocal, xLocal, yLocal, this->processDataNum);
                }
                else
                {
                    Muls(yLocal, xLocal, scalar, this->processDataNum);  // 2y
                    Exp(xLocal, xLocal, this->processDataNum);        //x = ey
                    Exp(yLocal, yLocal, this->processDataNum);        //y = e2y

                    scalar = 1.00;
                // Mul(yLocal, xLocal, xLocal, this->processDataNum);
                    Adds(yLocal, yLocal, scalar, this->processDataNum);
                    
                    scalar = 2.00;
                    Muls(xLocal, xLocal, scalar, this->processDataNum); 
                    Div(yLocal, xLocal, yLocal, this->processDataNum);
                }
                Mul(yLocal, dyLocal, yLocal, this->processDataNum);

            }
        }

        
        //   abs_y = np.abs(y)
        // if abs_y > 20:  # 根据实际需要调整阈值
        //  return np.exp(abs_y) / 2
        //else:
        //  exp_y = np.exp(y)
        //  return (exp_y / 2) * (1 + np.exp(-2 * y))
        

        
        // auto m_mask    = QueueMask.Get<uint8_t>();

        //DTYPE_Y scalar = 1.00;
        //Duplicate(m_zero, (DTYPE_X)(20.0), this->processDataNum);
        //Compare(m_mask, xLocal, m_zero, CMPMODE::LT, (this->processDataNum+255)/256*256);  //256字节对齐生成mask,小于0为1
        // Exp(yLocal, xLocal, this->processDataNum);   
        //Select(xLocal, m_mask, yLocal, xLocal, SELMODE::VSEL_TENSOR_TENSOR_MODE, this->processDataNum);


            // # y 是 asinhgrad(x) 的结果
            // # dy 是损失函数关于 y 的梯度
            // x = np.sinh(y)  # 计算 x = sinh(y)
            // grad_x = dy / np.sqrt(x**2 + 1)  # 计算 grad_x
            //  grad_x = dy / cosh(asinh(x))
        //}
        //Div(yLocal, dyLocal, yLocal, this->processDataNum);
        // Reciprocal(yLocal, yLocal, this->processDataNum);
        //Mul(yLocal, dyLocal, yLocal, this->processDataNum);

        outQueueY.EnQue<DTYPE_Y>(yLocal);
        inQueueX.FreeTensor(xLocal);
        inQueueDY.FreeTensor(dyLocal);

    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        //考生补充算子代码
        LocalTensor<DTYPE_Y> yLocal = outQueueY.DeQue<DTYPE_Y>();
        DataCopy(yGm[progress * this->tileDataNum], yLocal, this->processDataNum);
        outQueueY.FreeTensor(yLocal);
    }

private:
    TPipe pipe;
    //create queue for input, in this case depth is equal to buffer num
    TQue<QuePosition::VECIN, BUFFER_NUM> inQueueX;
    TQue<QuePosition::VECIN, BUFFER_NUM> inQueueDY;
    //create queue for output, in this case depth is equal to buffer num
    TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueY;
    GlobalTensor<DTYPE_X> xGm;
    GlobalTensor<DTYPE_DY> dyGm;
    GlobalTensor<DTYPE_Y> yGm;
    TBuf<QuePosition::VECCALC> QueueZero;  //,QueueMask

    //考生补充自定义成员变量
    uint32_t coreDataNum;
    uint32_t tileNum;
    uint32_t tileDataNum;
    uint32_t tailDataNum;
    uint32_t processDataNum;
};

extern "C" __global__ __aicore__ void asinh_grad(GM_ADDR x, GM_ADDR dy, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling) {
    GET_TILING_DATA(tiling_data, tiling);
    KernelAsinhGrad op;
    //补充init和process函数调用内容
    op.Init(x, dy, y, tiling_data.CoreDataNum, tiling_data.finalTileNum, tiling_data.tileDataNum, tiling_data.TailDataNum);
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
// call of kernel function
void asinh_grad_do(uint32_t blockDim, void *l2ctrl, void *stream, uint8_t *x, uint8_t *dy, uint8_t *y, 
                   uint8_t *workspace, uint8_t *tiling)
{
    asinh_grad<<<blockDim, l2ctrl, stream>>>(x, dy, y, workspace, tiling);
}
#endif
